// 在工具类 utils/dateFormat.js 中封装
function formatDate(date, format = 'yyyy-MM-dd HH:mm:ss') {
  // 如果是时间戳，先转为 Date 对象
  date = new Date(date);

  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 月份从0开始，补0
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  const ms = date.getMilliseconds()

  const padStr = (n, i = 2) => { return String(n).padStart(i, '0') }

  // 替换格式字符串中的占位符
  return format
    .replace('yyyy', padStr(year, 4))
    .replace('YYYY', padStr(year, 4))
    .replace('MM', padStr(month))
    .replace('M', month)
    .replace('dd', padStr(day))
    .replace('DD', padStr(day))
    .replace('D', day)
    .replace('d', day)
    .replace('hh', padStr(hour))
    .replace('HH', padStr(hour))
    .replace('H', hour)
    .replace('h', hour)
    .replace('mm', padStr(minute))
    .replace('ss', padStr(second))
    .replace('ms', padStr(second, 3));
}

module.exports = {
  formatDate
};